<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>报餐统计</title>
	
	<link rel="stylesheet" href="/scriptZIP/layui.min.css">
	<link rel="stylesheet" href="../css/common2.css">
	<link rel="stylesheet" href="../css/layui.css" />
	<style scoped>
		.hut_but_tz {
			display: inline-block;
			height: 38px;
			width: 108px;
			line-height: 38px;
			padding: 0 18px;
			background: url(../image/enter.png) no-repeat center center;
			color: #fff;
			white-space: nowrap;
			text-align: center;
			font-size: 14px;
			border: none;
			border-radius: 2px;
			cursor: pointer;
		}

		.search_box {
			display: flex;
			align-items: center;
		}

		.search_left {
			display: flex;
			align-items: center;
			margin-right: 30px;
		}

		.select_s {
			width: 100px;
			height: 35px;
			border: none;
			margin-right: 5px;
		}

		.search_name {
			height: 35px;
			max-width: 135px;
			padding: 0 5px;
			margin-right: 5px;
		}

		.table {
			width: 99%;
		}

		.four {
			width: auto;
		}

		.search {
			width: 15vw;
			max-width: 140px;
			height: 35px;
			padding-left: 10px;
			font-size: 14px;
			color: #686868;
			position: absolute;
			left: 20px;
			border: 1px solid;
			display: inline-block;
		}

		.search1 {
			height: 35px;
			max-width: 135px;
			padding: 0 5px;
			margin-right: 5px;
		}

		.meal-summary {
			bottom: 30px;
			font-size: 18px;
			font-weight: bold;
			text-align: left;
			background-color: rgba(255, 255, 255, 0.8);
			position: fixed;
			left: 15px;
			background: rgba(255, 255, 255, 0.95);
			border-radius: 10px;
			padding: 16px;
			box-shadow:
				0 4px 6px rgba(0, 0, 0, 0.1),
				0 1px 3px rgba(0, 0, 0, 0.08);
			border: 1px solid rgba(0, 0, 0, 0.05);
			backdrop-filter: blur(8px);
			font-family: 'Segoe UI', system-ui;
			min-width: 240px;
			z-index: 1000;
		}

		/* 新增内部布局容器 */
		.meal-summary>div {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 12px;
		}

		.meal-summary p {
			margin: 0;
			display: flex;
			justify-content: space-between;
			align-items: baseline;
			padding: 6px 0;
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);
		}

		.meal-summary p:last-child {
			border-bottom: none;
		}

		.meal-summary span {
			color: #1890ff;
			/* 改为科技蓝色系 */
			font-weight: 600;
			font-size: 20px;
			position: relative;
			padding-left: 24px;
		}

		.today-column {
			background-color: #ffeb3b !important;
			color: #000 !important;
			font-weight: bold;
			border: 2px solid red;
		}
	</style>
</head>

<body class="main-body">
	<div id="vue-root" style="margin-top:50px;">
		<div class="search_box">
			<div class="search_left">
				<select v-model="search.type" class="select_s">
					<option :value="undefined">全部</option>
					<option :value="1">午餐</option>
					<option :value="2">晚餐</option>
				</select>
				<input class="search_name" placeholder="请输入姓名（学员/老师）" v-model="search.name">

				<input placeholder="选择日期" readonly class="search1" v-model="date" id="Time" />

				<img src="../image/search.png" height="35" width="35" class="search_img" @click="getData0">
			</div>
			<div class="refresh" onclick="location.reload()" style="display: inline-block;">刷新</div>
		</div>
		<form enctype="multipart/form-data" id="form" ref="form" style="display: none;">
			<input type="file" name="file" id="file" @change="importExcel" ref="file"
				accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
		</form>
		<div class="table ">
			<table class="table_top">
				<thead>
					<tr>
						<th class="two">序号</th>
						<th>校区</th>
						<th>姓名（学员/老师）</th>
						<th class="two">餐食</th>
						<th v-for="(d,i) in dates" :key="i">{{dates[i]}} <br />
							<span style="font-size: 18px;margin-top: 2px;">星期{{weekdays[i]}}</span>
						</th>

					</tr>
				</thead>
				<tbody id="list">
					<tr v-for="(item,index) in list">
						<td style="width: 100px"><span v-text="index+1"></span></td>

						<td class="four" v-text="item.schoolName"></td>
						<td class="four" v-text="item.name"></td>

						<td class="four" v-text="item.type==1?'午餐':'晚餐'"></td>
						<!-- 动态渲染每天的餐食状态 -->
						<td v-for="(d, i) in dates" :key="i">
							<!-- 如果状态为 null，禁用输入框并显示提示 -->
							<input type="radio" v-model="item[`day${i + 1}Status`]" :value="'1'"
								:name="`day${i + 1}-radio-${index}`" :disabled="item[`day${i + 1}Status`] === null"
								@change="updateStatus(item, `day${i + 1}Status`, '1')" />
							<input type="radio" v-model="item[`day${i + 1}Status`]" :value="'0'"
								:name="`day${i + 1}-radio-${index}`" :disabled="item[`day${i + 1}Status`] === null"
								@change="updateStatus(item, `day${i + 1}Status`, '0')" />

							<!-- 显示 √ 或 X -->
							<span v-if="item[`day${i + 1}Status`] == '1'">√</span>
							<span v-else-if="item[`day${i + 1}Status`] == '0'">X</span>
							<span v-else>未报餐</span> <!-- 如果状态为 null，显示“未报餐” -->
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<div class="layui-inline">
			<div class="layui-input-inline">
				<input placeholder="选择下载月份" class="delete" id="monthPicker" v-model="selectedYearMonth" />
				<label @click="downloadTemplate" style="width: 120px;" class="delete long-background-img">下载导入模板</label>
				<label @click="downloadTemplate1" style="width: 120px;" class="delete long-background-img">下载报餐记录</label>
			</div>
		</div>


		<label class="delete long-background-img" for="file" v-if="able.import">导入报餐</label>

		<ul class="pagination" v-if="pages>1">
			<li>	
				<a v-if="pageNum!=1" @click="pageNum=1">«</a>
				<a class="pages-jump" v-if="pageNum!=1" @click="pageNum&#45;&#45;">‹</a>
				<a v-text="pageNum"></a>
				<a class="pages-jump" v-if="pageNum!=pages" @click="pageNum++">›</a>
				<a v-if="pageNum!=pages" @click="pageNum=pages">»</a>
			</li>

		</ul>
		<div style="float: right;margin-bottom: 20px;">
			总共{{total}}条记录
			<select class="ui-select init" style="height:32px" v-model="pageSize">
				<option :value="10">每页10条</option>
				<option :value="30">每页30条</option>
				<option :value="100">每页100条</option>
			</select>
		</div>

		<div class="meal-summary">
			<div style="display: flex; justify-content: space-between;">
				<!-- 原有统计 -->
				<div>
					<p>当天午餐共计: <span id="lunch-count">0</span>人</p>
					<p>当天晚餐共计: <span id="dinner-count">0</span>人</p>
				</div>


				<div>
					<p>教师午餐共计: <span id="teacher-lunch-count">0</span>人</p>
					<p>学生午餐共计: <span id="student-lunch-count">0</span>人</p>

				</div>
				<div>
					<p>教师晚餐共计: <span id="teacher-dinner-count">0</span>人</p>
					<p>学生晚餐共计: <span id="student-dinner-count">0</span>人</p>
				</div>
			</div>
		</div>

	</div>
	<script src="/scriptZIP/qs.min.js"></script>
	<script src="/scriptZIP/vue.min.js"></script>
	<script src="/scriptZIP/axios.min.js"></script>
	<script src="/scriptZIP/dayjs.min.js"></script>
	<!-- <script src="//unpkg.com/layui@2.6.8/dist/layui.js"></script> -->
	<script src="/lib/laydate/laydate.js"></script>
	<script src="/js/common.js"></script>
	<script src="/js/list.js"></script>
	<script src="/js/auth_util.js"></script>

	<script>
		function days(date) {
			var day = new Date(date).getDay(), a = [], i;
			date = dayjs(new Date(date));
			if (day == 0) day = 7;
			for (i = 1 - day; i < 8 - day; i++)
				a.push(date.add(i, 'day').format('YYYY-MM-DD'));
			return a;
		}

		function meal(title) {
			return {
				title: title,
				days: [0, 1, 2, 3, 4, 5, 6].map(function (i) {
					return { food: '', pics: [] };
				})
			};
		}
		var app = new Vue(merge({
			data: {
				weekdays: '一二三四五六日'.split(''),
				date: dayjs().format('YYYY-MM-DD'),
				selectedYearMonth: dayjs().format('YYYY-MM'), // 当前年月
				urls: {
				},


			},
			created: function () {
				abled('mealSubscription', this);
				this.search.date = this.date
				this.urls.list = '/pc/mealReservation/list/' + top_params().id;
				this.fetchTotalAmount();
				this.urls.imports = '/pc/mealReservation/import/' + top_params().id;
				
				this.getData();

			},
			methods: {
				getData0() {
					this.urls.list = '/pc/mealReservation/list/' + top_params().id;
					// 获取数据的逻辑
					this.fetchTotalAmount(); // 调用获取总金额的接口
					this.getData();
				},
				fetchTotalAmount() {
					// 调用后台接口，获取汇总金额
					axios.get('/pc/mealReservation/dailyStatistics?schoolId=' + top_params().id, { params: this.search }).then(function (res) {
						document.getElementById('lunch-count').innerText = res.data.totalLunch;
						document.getElementById('dinner-count').innerText = res.data.totalDinner;
						document.getElementById('teacher-lunch-count').innerText = res.data.teacherLunch;
							document.getElementById('student-lunch-count').innerText = res.data.studentLunch;
							document.getElementById('teacher-dinner-count').innerText = res.data.teacherDinner;
							document.getElementById('student-dinner-count').innerText = res.data.studentDinner;
					}.bind(this));
				},
				canModify(date) {
					// 获取当前时间
					let now = dayjs();
					let selectedDate = dayjs(date + " 22:00:00"); // 选中的日期的 22:00
					console.log(now.isBefore(selectedDate));
					return now.isBefore(selectedDate); // 只有在 22:00 之前才能修改
				},

				updateStatus(item, dayKey, newValue) {
					// 获取 dayKey 对应的索引，例如 day1Status => 1
					const dayIndex = parseInt(dayKey.replace('day', '').replace('Status', '')) - 1;
					const date = this.dates[dayIndex]; // 获取对应的日期
					var staffUserName = localStorage.getItem('staffUserName')

					if (staffUserName === 'null') {
						console.log("staffUserName 为空，跳过 canModify 校验");
					} else if (!this.canModify(date)) {
						alert("只能在前一天 22:00 前修改报餐状态");
						this.getData();
						return;
					}
					const originalStatus = item[dayKey];
					var payload = {
						studentId: item.studentId,
						date: date,
						type: item.type,
						status: newValue
					};

					axios.put('/pc/mealReservation/update', payload).then(function (res) {
						// alert("修改成功");
						layer.confirm('修改成功', { time: 3000, icon: 1 });
						this.getData();
					}.bind(this));
				},
				downloadTemplate() {
					if (!this.selectedYearMonth) {
						alert("请选择年月！");
						return;
					}
					const [year, month] = this.selectedYearMonth.split('-');

					axios.get('/pc/mealReservation/exportTemplate', {
						params: { year, month },
						responseType: 'blob' // 重要！指定响应类型为 blob
					}).then(response => {
						const blob = new Blob([response.data], { type: response.headers['content-type'] });
						const link = document.createElement('a');
						link.href = URL.createObjectURL(blob);
						link.download = `报餐模板_${year}_${month}.xlsx`; // 下载文件名
						link.click();
						URL.revokeObjectURL(link.href); // 释放资源
					}).catch(error => {
						console.error("下载失败：", error);
						alert("模板下载失败，请稍后重试！");
					});
				},

				downloadTemplate1() {
					if (!this.selectedYearMonth) {
						alert("请选择年月！");
						return;
					}
					const [year, month] = this.selectedYearMonth.split('-');
					var schoolId=top_params().id;

					axios.get('/pc/mealReservation/export', {
						params: { schoolId,year, month },
						responseType: 'blob' // 重要！指定响应类型为 blob
					}).then(response => {
						const blob = new Blob([response.data], { type: response.headers['content-type'] });
						const link = document.createElement('a');
						link.href = URL.createObjectURL(blob);
						link.download = `报餐导出表单校_${year}_${month}.xlsx`; // 下载文件名
						link.click();
						URL.revokeObjectURL(link.href); // 释放资源
					}).catch(error => {
						console.error("下载失败：", error);
						alert("模板下载失败，请稍后重试！");
					});
				},


			},
			computed: {
				dates: function () {
					return days(this.date);
				}
			},

		}));
		laydate.render({
			elem: '#Time',
			format: 'yyyy-MM-dd',
			done: function (value) {
				if (!value) {
					alert("必须选择一个日期")
			const today = dayjs().format('YYYY-MM-DD');
			app.date = today;
			app.search.date = today;
		} else {
			app.date = value;
			app.search.date = value;
		}
		 app.getData();
				// app.date = value;
				// app.search.date = value; // 同步更新搜索条件中的日期
				// app.getData();
			}
		});

		laydate.render({
			elem: '#monthPicker',
			type: 'month',
			done: function (value) {
				app.selectedYearMonth = value; // 更新 Vue 数据
			}
		});

	</script>


</body>

</html>